package com.xmg.boot.demo.bootlesson1.user.controller;

import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.xmg.boot.demo.bootcommon.utils.JwtUtils;
import com.xmg.boot.demo.bootlesson1.user.annotation.StartSwaggerScan;
import com.xmg.boot.demo.bootlesson1.user.entity.Result;
import com.xmg.boot.demo.bootlesson1.user.entity.ResultUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: ma
 * @CreateTime: 2023-11-23
 * @Description: TODO
 * @Version: 1.0
 */

@StartSwaggerScan
@RestController
public class JwtController {
    @ApiOperation("JWT生成 - path路径 /方式")
    @GetMapping("/login/{name}/{pwd}")
    public Result<String> Login(@PathVariable("name") String name, @PathVariable("pwd") String pwd) {
        Map<String, String> payload = new HashMap<>();
        payload.put("id", "9999");
        payload.put("name", name);
        payload.put("role",pwd);
        //生成令牌
        String token = JwtUtils.sign(payload);
        return ResultUtil.success("登录成功", token);
    }


    @ApiOperation("JWT生成 - request路径 ？方式")
    @GetMapping("/login1")
    public Result<String> Login1(@RequestParam("name") String name, @RequestParam("pwd") String pwd) {
        Map<String, String> payload = new HashMap<>();
        payload.put("id", "9999");
        payload.put("name", name);
        payload.put("role",pwd);
        //生成令牌
        String token = JwtUtils.sign(payload);
        return ResultUtil.success("登录成功", token);
    }


    @ApiOperation("测试token")
    @PostMapping("/testJwt")
    public Result<String> testJwt(@RequestParam("token") String token){
        System.out.println("token:"+token);
        //验证令牌
        DecodedJWT verify=JwtUtils.getPayload(token);
        Map<String, Claim> map= verify.getClaims();

        System.out.println(verify.getClaim("id").asString());
        System.out.println(verify.getClaim("name").asString());
        System.out.println(verify.getClaim("role").asString());

        return ResultUtil.success();
    }
}
